<?php

// 公共助手函数

use fq\request\LoadRequest;
use Symfony\Component\VarExporter\VarExporter;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @param int $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}


if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            header('HTTP/1.1 403 Forbidden');
            exit;
        }
    }
}

//(重构版)万能高佣转链API接口
// http://api.web.ecapi.cn/taoke/doItemHighCommissionPromotionLinkByAll?apkey=登录会员中心查看&tbname=xxx&pid=mm_0000_0000_000&content=xxxxx
function get_item_info($content, $relationid = 0, $remark = '')
{
//    使用剪切板识别
    $content = hdk_parse($content);
    if (!$content) return false;
    trace('hdk:' . $content, 'error');
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'pid' => 'mm_1520060136_2232550319_111183800425',//常规
        'content' => $content,
        'tpwd' => 1,
        'hasiteminfo' => 1,
        'need_new_item_id' => 1,
    ];
    //渠道id
    if ($relationid > 10) {
        $data['relationid'] = $relationid;
        $data['pid'] = 'mm_1520060136_2232550319_111431400345';//淘客基地渠道
//        $data['pid'] = 'mm_1520060136_2232550319_111465750075';//淘客基地渠道
    }
    $url = "http://api.web.ecapi.cn/taoke/doItemHighCommissionPromotionLinkByAll?";
    trace('url:' . $url, 'error');
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    trace($content, 'error');
    if (!empty($content['data'])) {
        db('tpwdReport')->insert(['pid' => $data['pid'], 'tpwd' => $content['data']['tpwd'], 'remark' => $remark]);
        $itemInfo = $content['data']['item_info'];
        unset($content['data']['item_info']);
        $itemInfo = array_merge(['youhuiquan' => 0], $content['data'], $itemInfo);
        trace('iteminfo:', 'error');
        trace($itemInfo, 'error');
        return $itemInfo;
    }
}

/**
 * 淘客官方活动(饿了么)推广
 * @param $content
 * @param int $relationid
 * @return mixed
 */
function get_activity_info($content = 20150318020002597, $relationid = 0, $remark = '')
{
    if ($content == '') $content = 20150318020002597;
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'pid' => 'mm_1520060136_2232550319_111183800425',//常规
        'activity_material_id' => $content,
        'hastpwd' => 1,
        'tpwd_title' => '一个好商品',
    ];
//    http://api.web.ecapi.cn/taoke/getTbkActivityInfo?apkey=登录会员中心查看&tbname=xxxx&pid=mm_123456_456789_789132&activity_material_id=xxxx&relation_id=xxxx
    //渠道id
    if ($relationid > 10) {
        $data['relation_id'] = $relationid;
        trace($data['relation_id'], 'error');
        $data['pid'] = 'mm_1520060136_2232550319_111464400277';//渠道
//        $data['pid'] = 'mm_1520060136_2232550319_111723250244';//Eportal
    }
    $url = "http://api.web.ecapi.cn/taoke/getTbkActivityInfo?";
//    dump($data);
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);

    $content = json_decode($result, true);
//    dump($content);
    trace('活动ffff', 'error');
    trace($content, 'error');
    if (!empty($content['data'])) {
//        db('tpwdReport')->insert(['pid' => $data['pid'], 'tpwd' => $content['data']['tpwd'], 'remark' => $remark]);
        $reg = "#([a-zA-Z0-9]{11})#isu";
        if (preg_match($reg, $content['data']['tpwd'], $m) !== false) {
            return "zh/ CZ5487({$m[1]})";
//            return "29￥ CZ0001 {$m[1]})";
        }
    }
}

function get_publisher_info()
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'info_type' => '1',
        'relation_app' => 'common',
        'page_size' => 100,

    ];
    $url = "http://api.web.ecapi.cn/taoke/getTbkPublisherInfo?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
//    return $content;
    if (isset($content['data']['inviter_list']['map_data'])) {
        return $content['data']['inviter_list']['map_data'];
    }

}

function get_invite_code()
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'relationapp' => 'common',
        'codetype' => '1',

    ];
    $url = "http://api.web.ecapi.cn/taoke/getInviteCode?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
}

function get_relation_oauth_tpwd($rtag = '123456')
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'invitercode' => 'J8F5E6',
        'rtag' => $rtag,
        'content' => '一键授权备案',

    ];
    $url = "http://api.web.ecapi.cn/taoke/getRelationOauthTpwd?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
}

// 大淘客api
function dtk_request($host, $version, $params, $type = "GET")
{
    $appKey = '5d9afc56d2ab8';
    $appSecret = 'a8a69ce671ef5af198fd61be5abe800c';

    if ($host == '' || $appKey == '' || $appSecret == '' || $version == '') {
        return json_encode(array('code' => -10001, 'msg' => "请完善参数"));
    }
    $type = strtoupper($type);
    if (!in_array($type, array("GET", "POST"))) {
        return json_encode(array('code' => -10001, 'msg' => "只支持GET/POST请求"));
    }
    $data = [
        'appKey' => $appKey,
        'version' => $version,
    ];
    $data = array_merge($params, $data);
    ksort($data);
    $str = '';
    foreach ($data as $k => $v) {
        $str .= '&' . $k . '=' . $v;
    }
    $str = trim($str, '&');
    $data['sign'] = strtoupper(md5($str . '&key=' . $appSecret));
    try {
        if ($type == 'POST') {
            //拼接请求地址
            $url = $host;
            //执行请求获取数据
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $header = [
                'Content-Type: application/json'
            ];
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            $output = curl_exec($ch);
            $a = curl_error($ch);
            if (!empty($a)) {
                return json_encode(array('code' => -10003, 'msg' => $a));
            }
            curl_close($ch);
            return $output;
        } else {
            //拼接请求地址
            $url = $host . '?' . http_build_query($data);
            //执行请求获取数据
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $output = curl_exec($ch);
            $a = curl_error($ch);
            if (!empty($a)) {
                return json_encode(array('code' => -10003, 'msg' => $a));
            }
            curl_close($ch);
            return $output;
        }
    } catch (Exception $e) {
        trace($e->getMessage());
        return json_encode(array('code' => -10002, 'msg' => "请求超时或异常，请重试"));
    }
}


function create_tpwd($content)
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        //        'tbname' => 'tb370655212',
        'title' => '优惠商品，抢先购买',//常规
        'url' => urlencode($content),
    ];

    $url = "http://api.web.ecapi.cn/taoke/createTaoPwd?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    trace($content, 'error');
    if (!empty($content['data'])) {
        return $content['data']['tpwd_str'];
    }
}

/** 淘口令回流数据查询
 * @param $pid
 * @param $tpwd
 * @return mixed
 */
function get_tpwd_report($pid, $tpwd)
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'pid' => $pid,//常规
        'tao_password' => $tpwd,
    ];

    $url = "http://api.web.ecapi.cn/taoke/getTpwdReport?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    trace($content, 'error');
    if (!empty($content['data'])) {
        return $content['data'];
    }

}

/**偷单检测
 * @param $pid
 * @param $tpwd
 * @return mixed
 */
function check_pid_legal($pid, $tpwd)
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'pid' => $pid,//常规
        'content' => $tpwd,
    ];

    $url = "http://api.web.ecapi.cn/taoke/checkPidLegal?";
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
    trace($content, 'error');
    if (!empty($content['data'])) {
        return $content['data'];
    }

}

/**
 * 淘系订单查询
 * 场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
 */
function order_details($startTime, $endTime)
{
    $orders1 = [];
    $host = 'https://openapi.dataoke.com/api/tb-service/get-order-details';
    $version = 'v1.0.0';
    $params['queryType'] = 2;
    $params['startTime'] = $startTime;
    $params['endTime'] = $endTime;
    $params['pageSize'] = 100;

    //常规订单
    $params['orderScene'] = 1;
    $result = dtk_request($host, $version, $params);
    $result = json_decode($result, true);
    if (isset($result['data']['results']['publisher_order_dto'])) {
        $orders1 = $result['data']['results']['publisher_order_dto'];
        while ($result['data']['has_next'] == true) {
            $params['pageNo'] = $result['data']['page_no'] + 1;
            $params['positionIndex'] = $result['data']['position_index'];
            $result = dtk_request($host, $version, $params);
            $result = json_decode($result, true);
            $orders1 = array_merge($orders1, $result['data']['results']['publisher_order_dto']);
        }
        foreach ($orders1 as $order) {
            try {
                $order['update_time'] = date('Y-m-d H:i:s');
                db('orderDetails')->strict(false)->insert($order, true);
            } catch (\Exception $e) {
                file_put_contents('/tmp/order_details', $e->getMessage(), 8);
            }
        }
//        dump($orders1);
    }

    //渠道订单
    $params['orderScene'] = 2;
    $result = dtk_request($host, $version, $params);
    $result = json_decode($result, true);
    if (isset($result['data']['results']['publisher_order_dto'])) {
        $orders2 = $result['data']['results']['publisher_order_dto'];
        while ($result['data']['has_next'] == true) {
            $params['pageNo'] = $result['data']['page_no'] + 1;
            $params['positionIndex'] = $result['data']['position_index'];
            $result = dtk_request($host, $version, $params);
            $result = json_decode($result, true);
            $orders2 = array_merge($orders2, $result['data']['results']['publisher_order_dto']);
        }

        foreach ($orders2 as $order) {
            try {
                $order['update_time'] = date('Y-m-d H:i:s');
                db('orderDetails')->strict(false)->insert($order, true);
            } catch (\Exception $e) {
                file_put_contents('/tmp/order_details', $e->getMessage(), 8);
            }
        }

    }
    return $orders1;


}

function meituan_v2($eid = 'common')
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'eid' => $eid,
    ];
    dump($eid);
    $url = "http://api.web.ecapi.cn/platform/meituan_v2?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
}

function dm_order($eid = '')
{
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'eid' => $eid,
        'page' => 1,
        'pageSize' => 100
    ];
    $url = "http://api.web.ecapi.cn/platform/dmOrder?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
}

//淘口令格式化入库
function tpwd_format($tpwd, $pid = 0, $relationid = 0)
{
    $reg = "#([a-zA-Z0-9]{11})#isu";
    if (preg_match($reg, $tpwd, $m) !== false) {
        return $m;
    }
}

//查询超级红包发放个数
function get_red_packet($date = 0)
{
    if ($date == 0) $date = date('Ymd');
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'biz_date' => $date,//统计日期
        'activity_id' => '1306',
        'page_size' => 100,

    ];
    $url = "http://api.web.ecapi.cn/taoke/getSRedpacketSendInfo?";
    trace($data, 'error');
    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
}

//淘礼金创建
function create_taolijin($itemid = 0, $money = 1, $num = 1)
{
    $secret = 'c68903937449446f4c892a05f3892765';
    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'tbname' => 'tb370655212',
        'tbappkey' => 32823552,
        'tbappsecret' => $secret,//有淘礼金权限的Appkey，不知道有没有的登录：open.taobao.com，进行查看
        'adzoneid' => '111186000312',//妈妈广告位Id，PID第三段
        'itemid' => $itemid,
        'end_time' => date('Y-m-d 23:59:59'),
        'start_time' => date('Y-m-d H:i:s'),
        'num' => $num,
        'name' => '淘礼金来了',
        'win_limit' => 1,//单用户累计中奖次数上限
        'secure' => 'true',
        'money' => 1,
        'useThreshold' => 5,
    ];
    $url = "http://api.web.ecapi.cn/taoke/create_taolijin?";
    $params = http_build_query($data);
    dump($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
}


function tlj_create($item_id, $money = 1, $_money = 0, $username = '', $num = 1)
{
    vendor("taobao.TopSdk");
    $adzoneId = '111186000312';
    $c = new \TopClient;
    $c->appkey = '32823552';
    $c->secretKey = 'c68903937449446f4c892a05f3892765';
    $c->format = 'json';
    $startTime = date('Y-m-d H:i:s');
    $endTime = date('Y-m-d H:i:s', strtotime(" +1 hour"));

    $req = new \TbkDgVegasTljCreateRequest;
    $req->setAdzoneId($adzoneId);
    $req->setItemId($item_id);
    $req->setTotalNum($num);
    $req->setName('淘礼金');
    $req->setUserTotalWinNumLimit("1");
    $req->setSecuritySwitch('true');
    $req->setPerFace($money);
    $req->setUseEndTimeMode("2");
    $req->setUseStartTime($startTime);
    $req->setUseEndTime($endTime);
    $req->setSendStartTime($startTime);
    $req->setSendEndTime($endTime);

    if ($_money > 0) {
        $req->setUseThreshold($_money);
    }
    $resp = $c->execute($req);

    $tlj = [
        'adzone_id' => $adzoneId,
        'item_id' => $item_id,
        'per_face' => $money,
        'use_threshold' => $_money,
        'start_time' => $startTime,
        'end_time' => $endTime,
        'username' => $username,
    ];
    $tpwd = false;
    trace($resp, 'error');
    if ($resp->result->success) {
        $rights_id = $resp->result->model->rights_id;
        $tlj['available_fee'] = $resp->result->model->available_fee;
        $tlj['rights_id'] = $resp->result->model->rights_id;
        $tlj['send_url'] = $resp->result->model->send_url;
        $tlj['vegas_code'] = $resp->result->model->vegas_code;
        $req = new \TbkTpwdCreateRequest;
        $req->setUserId("gzx19880218");
        $req->setText('淘礼金来了');
        $req->setUrl($tlj['send_url']);
        $req->setLogo("");
        $resp = $c->execute($req);
        trace($resp, 'info');
        $tpwd = $resp->data->password_simple;
        $tlj['tpwd'] = $tpwd;
        db('tljReport')->insert($tlj);
    } else {
        file_put_contents('/tmp/msginfo', $resp->result->msg_info);
        $tlj['msg_info'] = $resp->result->msg_info;
    }

    return $tlj;
}

function tlj_report($rightsId){
    vendor("taobao.TopSdk");
    $c = new \TopClient;
    $adzoneId = '111186000312';
    $c->appkey = '32823552';
    $c->secretKey = 'c68903937449446f4c892a05f3892765';
    $c->format = 'json';
    $req = new \TbkDgVegasTljReportRequest;
    $req->setRightsId($rightsId);
    $req->setAdzoneId($adzoneId);
    $resp = $c->execute($req);
    return (array)$resp;
}

function tlj_stop($rightsId){
    vendor("taobao.TopSdk");
    $c = new \TopClient;
    $adzoneId = '111186000312';
    $c->appkey = '32823552';
    $c->secretKey = 'c68903937449446f4c892a05f3892765';
    $req = new \TbkDgVegasTljStopRequest;
    $req->setRightsId($rightsId);
    $req->setAdzoneId($adzoneId);
    $resp = $c->execute($req);
    return (array)$resp;
}

//实时线报入库
function wire_report()
{
    $url = 'http://v2.api.haodanku.com/wire_report?apikey=sylar&min_size=100&min_id=1';
    $content = file_get_contents($url);
    return $content;
}

//单品详情API
function item_detail($itemid)
{

    $itemDetail = db('itemDetail')->find();
    $keys = array_keys($itemDetail);

    $url = "http://v2.api.haodanku.com/item_detail?apikey=sylar&itemid=$itemid";
    $contents = file_get_contents($url);

    $item = json_decode($contents, true);
//    halt($item);
    $itemkeys = array_keys($item['data']);
    $diff = array_diff($itemkeys, $keys);
    if (isset($item['data']['shop_score'])) {
        $item['data']['shop_score'] = json_encode($item['data']['shop_score']);
    }

    $item['data']['others'] = implode(',', $diff);

    db('itemDetail')->strict(false)
        ->insert($item['data'], true);

    return $item['data'];
}

function get_tpwd($itemid, $relationId = '')
{
    $url = 'http://v2.api.haodanku.com/ratesurl';
    $data = [
        'apikey' => 'sylar',
        'tb_name' => 'tb370655212',
        'itemid' => $itemid,
        'pid' => 'mm_1520060136_2232550319_111431400345',
        'get_taoword' => 1,
        //        'me'=>1,
        'title' => '淘宝的商品'
    ];
    //是否渠道id
    if ($relationId) {
        $data['relation_id'] = $relationId;
    }
    trace('get_tpwd', 'error');
    trace($data, 'error');
    file_put_contents('/tmp/xxy', 'error');
    $contents = file_post_contents($url, $data);
    file_put_contents('/tmp/xxy', $contents);
    $contents = json_decode($contents, true);
    if (isset($contents['data']['taoword'])) {
        return $contents['data']['taoword'];
    }

}

/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function file_post_contents($url, $post_data)
{

    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 2 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}

//京东商品转链,只支持商品id
function get_jditems_link($material_id)
{
    $url = 'http://v2.api.haodanku.com/get_jditems_link';
    $data = [
        'apikey' => 'sylar',
        'material_id' => $material_id,
        'union_id' => '2020989427',

    ];


    $contents = file_post_contents($url, $data);
    $contents = json_decode($contents, true);
    trace($contents);
    if (isset($contents['data']['short_url'])) {
        return ($contents['data']['short_url']);
    }

}


function jd_url($content, $positionId = '9876543210')
{
    $url = "http://api.web.ecapi.cn/jingdong/doItemCpsUrlWithContent?";

    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'content' => $content,
        'key_id' => 'J4882890883211085',
        'positionId' => $positionId,
        'autoSearch' => 1,
    ];

    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    trace($content);
    if (isset($content['data'])) {
        return $content['data'];
    }
}


/**
 * 淘系订单查询
 * 场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
 */
function jd_order_details($startTime, $endTime)
{
    $host = 'https://openapi.dataoke.com/api/dels/jd/order/get-official-order-list';
    $version = 'v1.0.0';
    $params['type'] = 1;
    $params['startTime'] = $startTime;
    $params['endTime'] = $endTime;
    $params['pageSize'] = 100;
    $params['key'] = 'dfb1d213da0d7d78d6e94fe85d45585096c521f2492a845c903007a3e069d0a4185983bed66a34d9';


    $result = dtk_request($host, $version, $params);
    $result = json_decode($result, true);
    return $result;

}


function curl_helper($url, $data = null, $header = [], $cookies = "", $method = 'GET')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_COOKIE, $cookies);
    switch ($method) {
        case  "GET":
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            break;
        case  "POST":
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case  "PUT":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case  "DELETE":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case  "PATCH":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case  "TRACE":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "TRACE");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case  "OPTIONS":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "OPTIONS");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case  "HEAD":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "HEAD");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        default :
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $response = curl_exec($ch);
    $output = [];
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    // 根据头大小去获取头信息内容
    $output['header'] = substr($response, 0, $headerSize);
    $output['body'] = substr($response, $headerSize, strlen($response) - $headerSize);
    $output['detail'] = curl_getinfo($ch);
    curl_close($ch);
    return $output;
}


function douyin($url)
{
    if (preg_match('/v.douyin.com\/(.*?)\//', $url, $match)) {
        $url = "https://v.douyin.com/" . $match[1] . "/";
        $title = input('title');
        $title = substr($title, 0, strpos($title, 'http'));
        $html = curl_helper($url);
        $url = $html['detail']['redirect_url'];
        if (preg_match('/video\/(.*?)\//', $url, $match_vid)) {
            $video_id = $match_vid[1];
            $html = curl_helper("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" . $video_id, null, ['user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36']);
            $videoObj = json_decode($html['body'], true);
            if ($videoObj['status_code'] == 0) {
                $videoUri = $videoObj['item_list'][0]['video']['play_addr']['url_list'][0];
                if ($videoUri) {
                    $url = str_replace('aweme.snssdk.com/aweme/v1/playwm', 'aweme.snssdk.com/aweme/v1/play', $videoUri);
                    $html = curl_helper($url, null, ['user-agent:Aweme/26006 CFNetwork/902.2 Darwin/17.7.0']);
                    $video = str_replace('http://', 'https://', $html['detail']['redirect_url']);
                    $name = substr($html['detail']['url'], 49, 32) . '.mp4';
                    return $video;
                }
            }
        }
    }
}

function cinema($userid = '', $username = '', $mobile = '')
{
    $url = "http://api.web.ecapi.cn/ls/getCinemaH5Url?";

    $data = [
        'apkey' => '6a9ffd88-17a3-9f54-0bb7-b91a81405862',
        'user_id' => $userid,
        'nickname' => $mobile,
        'mobile' => $mobile,
    ];

    $params = http_build_query($data);
    $result = file_get_contents($url . $params);
    $content = json_decode($result, true);
    return $content;
    if (isset($content['data'])) {
        return $content['data'];
    }
}

//剪切板识别商品链接
function parse($content)
{
    $data = [
        'appKey' => "5d9afc56d2ab8",
        'version' => "v1.0.0",
        'content' => $content,
    ];
    $host = "https://openapi.dataoke.com/api/dels/kit/contentParse";
    $url = $host . '?' . http_build_query($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $output = curl_exec($ch);
    $a = curl_error($ch);
    curl_close($ch);
    $item = json_decode($output, true);
    trace($output, 'error');
    if (isset($item['data']['itemId']))
        return $item['data']['itemId'];
}

//好单库的剪切板识别
function hdk_parse($content)
{
    $CONFIG['app_id'] = '20221038';
    $CONFIG['app_secret'] = 'd82a1e0b42151fadace2cb62761ce355';
    $request = new LoadRequest($CONFIG['app_id'], $CONFIG['app_secret']);
    $requestParam = new \fq\request\param\AnalyzeClipboard();
    $requestParam->setContent($content);//待识别文案
    $requestParam->setIsChange(1);//是否转换口令或分享链接：0 否(默认)、1 是
    $requestParam->setTbName('tb370655212');//好单库后台已授权的淘宝昵称
    $requestParam->setTbPid('mm_1520060136_2235300245_114610950130');
    $result = $request->run($requestParam);

    trace($result, 'error');
    $result = json_decode($result, true);
    return $result;

    if (!isset($result['data']['item_url'])) {
        return false;
    }
    return $result['data']['item_url'];

}

function isMobile($str)
{
    return preg_match("/^1[3-9]\d{9}$/", $str) ? true : false;
}

//好单库的剪切板识别
function hdk_jd($content)
{
    $CONFIG['app_id'] = '20221038';
    $CONFIG['app_secret'] = 'd82a1e0b42151fadace2cb62761ce355';
    $request = new LoadRequest($CONFIG['app_id'], $CONFIG['app_secret']);
    $requestParam = new \fq\request\param\AnalyzeClipboard();
    $requestParam->setContent($content);//待识别文案
    $requestParam->setIsChange(1);//是否转换口令或分享链接：0 否(默认)、1 是
    $requestParam->setJdUnionId('2020989427');//京东联盟id
    $requestParam->setJdPid('2020989427_4100569006_3004015769');//京东pid
    return $request->run($requestParam);

}

function jd_detail($text)
{
    $begin = strpos($text, 'https://3.cn');

    $content = substr($text, $begin, 21);
    if (!$content) return false;

    $cookie = config('site.hdk_cookie');
    $userAgent = config('site.hdk_agent');
    $url = 'https://publish.haodanku.com/toolapi/TransitionDdate_jd';
    $referer = 'https://www.haodanku.com/';
    $data = [
        'content' => $content,
        'sid' => '',
        'pid' => 1,
        'content_type' => '2020989427_4100569006_3004015769',
        'unionid' => 2020989427,
    ];
    $options = [
        'http' => [
            'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
                "Cookie: $cookie\r\n" .
                "User-Agent: $userAgent\r\n" .
                "Referer: $referer",
            'method' => 'POST',
            'content' => http_build_query($data),
        ],
    ];
    $context = stream_context_create($options);
    $res = file_get_contents($url, false, $context);

    $result = json_decode($res, true);
    if($result['msg'] == 'SUCCESS'){
        return str_replace($content, $result['data'], $result['value']);
    }else{
        return $res;
    }


}

//好单库的工具接口破解
//需要定期维护cookie
function hdk_taoword($content)
{
    $cookie = config('site.hdk_cookie');
    $userAgent = config('site.hdk_agent');
    $url = config('site.hdk_url');
    $referer = config('site.hdk_referer');
    $data = [
        'taoword' => $content,
        'request_head' => 'https',
        'analysis_taoword_type' => 1,
        'content_type' => 0,
//            'is_tlj'=>1,
    ];
    $options = [
        'http' => [
            'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
                "Cookie: $cookie\r\n" .
                "User-Agent: $userAgent\r\n" .
                "Referer: $referer",
            'method' => 'POST',
            'content' => http_build_query($data),
        ],
    ];
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return json_decode($result, true);
}

